package com.springmvc.platform.base.service.impl;

import com.springmvc.platform.base.domain.BaseDomain;
import com.springmvc.platform.base.imapper.IMapper;
import com.springmvc.platform.base.service.BaseService;
import com.springmvc.platform.base.shiro.WebSubjectUtil;
import com.springmvc.platform.util.BeanUtil;

import java.util.Date;
import java.util.List;

/**
 * @author zhouhong 基本crud类
 * @create 2017/10/25
 * @modify
 */
public abstract class BaseServiceImpl<T extends BaseDomain> implements BaseService<T> {
    public abstract IMapper<T> getBaseMapper();
    public List<T> query(T recond) {
        return getBaseMapper().select(recond);
    }

    public T queryById(Long id) {
        return getBaseMapper().selectByPrimaryKey(id);
    }

    public List<T> queryAll() {
        return getBaseMapper().selectAll();
    }

    public int queryCount(T record) {
        return getBaseMapper().selectCount(record);
    }

    public int add(T record) {
        String userCode=WebSubjectUtil.getUser().getUserCode()==null?"":WebSubjectUtil.getUser().getUserCode();
        Date currentDate=new Date();
        record.setCreateTime(currentDate);
        record.setDeleted(0);
        record.setLastModifyBy(userCode);
        record.setLastModifyTime(currentDate);
        record.setCreateBy(userCode);
        return getBaseMapper().insert(record);
    }

    public int updateById(T record) {
        String userCode=WebSubjectUtil.getUser().getUserCode()==null?"":WebSubjectUtil.getUser().getUserCode();
        Date currentDate=new Date();
        record.setLastModifyBy(userCode);
        record.setLastModifyTime(currentDate);
        return getBaseMapper().updateByPrimaryKey(record);
    }

    public int remove(T record) {
        //根据要删除的数据ID查询出原始数据并进行必要数据赋值
        T oldRecord=getBaseMapper().selectByPrimaryKey(record.getId());
        if(!BeanUtil.isEmpty(oldRecord)){
            String userCode=WebSubjectUtil.getUser().getUserCode()==null?"":WebSubjectUtil.getUser().getUserCode();
            Date currentDate=new Date();
            oldRecord.setLastModifyBy(userCode);
            oldRecord.setLastModifyTime(currentDate);
            oldRecord.setDeleted(1);
        }
        return getBaseMapper().updateByPrimaryKey(oldRecord);
    }

    public int addAll(List<T> list) {
        return 0;
    }
}
